package middleware

import (
	"forum/internal/application"
	"forum/internal/common/config"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
)

type AuthMiddlewareBuilder struct {
	JwtImService application.JwtService
	paths        []string
}

func NewAuthMiddlewareBuilder(jwtHandler application.JwtService) *AuthMiddlewareBuilder {
	return &AuthMiddlewareBuilder{
		JwtImService: jwtHandler,
	}
}

func (l *AuthMiddlewareBuilder) Ignore(path string) *AuthMiddlewareBuilder {
	l.paths = append(l.paths, path)
	return l
}

func (l *AuthMiddlewareBuilder) Build() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		for _, path := range l.paths {
			if path == ctx.Request.URL.Path {
				return
			}
		}

		tokenString := l.JwtImService.ExtractToken(ctx)
		var claim application.UserClaim
		token, err := jwt.ParseWithClaims(tokenString, &claim, func(token *jwt.Token) (interface{}, error) {
			return config.ShortJwtTokenKey, nil
		})
		if err != nil {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		//没登录
		if token == nil || !token.Valid {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		//验证Useragent
		if claim.UserAgent != ctx.Request.UserAgent() {
			//严重的安全问题
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		ctx.Set("claim", claim)
	}
}
